<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, ref } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'
import { AntDeleteOutlined, AntPlusOutlined, AntUploadOutlined } from '@vben/icons'

import { useDebounceFn } from '@vueuse/core'
import { Button, Input, message, Popconfirm, Tag } from 'ant-design-vue'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getAdminList, getSupplyList, getWarehouseList } from '#/api/common'
// API 更改为 mstockin
import { AuditMstockIn, batchImportStockin, daochuDetail, daochuList, doMstockinDelete, getMstockinList, ReverseMstockIn } from '#/api/mstockin'

import Form from './modules/form.vue'

interface RowType {
  [key: string]: any
}
const params = ref<any>({
  quick_search: '',
})
const selectedRows = ref<RowType[]>([])
const formData = ref<any>({})
// 关键字和加载状态，适配新字段
const keyword = ref({
  supply_id: '',
  posted_realname: '',
  created_admin_id: '',
  warehouse_name: '',
})

// 获取ApiSelect选项的函数
const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.supply_id,
    select: true,
  })
  return list.map((item: any) => ({ label: item.SupplyNa, value: item.id }))
}

const fetchPostedAdminOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.posted_realname,
    select: true,
  })
  return list.map((item: any) => ({ label: item.realname, value: item.id }))
}

const fetchCreatedAdminOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.created_admin_id,
    select: true,
  })
  return list.map((item: any) => ({ label: item.realname, value: item.id }))
}

const fetchWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getWarehouseList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.warehouse_name,
    select: true,
  })
  return list.map((item: any) => ({ label: `${item.warehouse_code}/${item.warehouse_name}`, value: item.id }))
}

// 获取选中行的ID
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

// 审核按钮禁用逻辑
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || !selectedRows.value.every((row: any) => row.Posted == 0)
})

// 反审按钮禁用逻辑
const isDisabledAgainst = computed(() => {
  return selectedRows.value.length <= 0 || !selectedRows.value.every((row: any) => row.Posted != 0)
})

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '入库单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'record_date',
      label: '入库日期',
      operator: 'RANGE',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'Manualid',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'Planid',
      label: '生产制单',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'GoodsNo',
      label: '货号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'warehouse_name',
      label: '入库仓库',
      operator: 'false',
      componentProps: () => ({
        api: fetchWarehouseOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.warehouse_name = value
        }, 300),
        params: {
          keyword: keyword.value.warehouse_name || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.warehouse_name = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'supply_id',
      label: '加工厂',
      operator: '=',
      componentProps: () => ({
        api: fetchSupplyOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value
        }, 300),
        params: { keyword: keyword.value.supply_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.supply_id = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'Operator',
      label: '创建人',
      operator: '=',
      componentProps: () => ({
        api: fetchCreatedAdminOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.created_admin_id = value
        }, 300),
        params: { keyword: keyword.value.created_admin_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.created_admin_id = ''
        },
      }),
    },
    // {
    //   component: 'ApiSelect',
    //   fieldName: 'posted_realname',
    //   label: '审核人',
    //   operator: 'false',
    //   componentProps: () => ({
    //     api: fetchPostedAdminOptions,
    //     filterOption: false,
    //     onSearch: useDebounceFn((value: string) => {
    //       keyword.value.posted_realname = value
    //     }, 300),
    //     params: { keyword: keyword.value.posted_realname || undefined },
    //     allowClear: true,
    //     showSearch: true,
    //     immediate: false,
    //     alwaysLoad: true,
    //     visibleEvent: 'onFocus',
    //     onDropdownVisibleChange: (open: boolean) => {
    //       if (open) keyword.value.posted_realname = ''
    //     },
    //   }),
    // },
    {
      component: 'Select',
      fieldName: 'Posted',
      label: '审核状态',
      operator: '=',
      componentProps: {
        options: [
          { label: '未审核', value: '0' },
          { label: '已审核', value: '1' },
        ],
        placeholder: '请选择',
        allowClear: true,
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    isHover: true,
  },
  columnConfig: { useKey: true },
  rowStyle({ row }) {
    if (row.Posted == '0') {
      return { color: 'red' }
    }
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'record_sn', width: 110, title: '入库单号', fixed: 'left' },
    { field: 'id', width: 70, title: 'ID' },
    { field: 'record_date', width: 110, title: '入库日期' },
    { field: 'Manualid', width: 110, title: '手工单号' },
    { field: 'warehouse_name', width: 110, title: '入库仓库' },
    { field: 'SupplyCode', width: 110, title: '工序厂编号' },
    { field: 'SupplyNa', width: 110, title: '加工厂' },
    { field: 'Planid', width: 120, title: '生产制单' },
    { field: 'goods_code', width: 120, title: '简码' },
    { field: 'poSupplyCode', width: 120, title: '制单工厂编码' },
    { field: 'poSupplyNa', width: 120, title: '制单工厂名称' },
    { field: 'GoodsNo', width: 100, title: '货号' },
    { field: 'process_name', width: 100, title: '工序' },
    { field: 'total_num', width: 100, title: '数量' },
    { field: 'total_price', width: 100, title: '总额' },
    { field: 'InputDate', width: 140, title: '录入日期' },
    { field: 'create_realname', width: 110, title: '创建人' },
    { field: 'PostedDate', width: 140, title: '审核日期' },
    { field: 'posted_realname', width: 110, title: '审核人' },
    { field: 'Remark', width: 120, title: '备注' },
    { field: 'Posted', width: 110, title: '审核状态', slots: { default: 'postStatus' } },
    { field: 'operation', fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 130 },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const body = {
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        }
        const { list, total } = await getMstockinList(body)
        return { items: list, total }
      },
      delete: async ({ body }) => {
        const ids = body.removeRecords.map((item: any) => item.id)
        await doMstockinDelete({ ids })
      },
    },
    sort: true,
    delete: true,
  },
  sortConfig: { defaultSort, remote: true },
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'mstockin_list',
  customConfig: {
    storage: true,
  },
}

// 获取审核状态的颜色和文本
const getPostStatusColor = (posted: number) => {
  return posted == 0 ? 'warning' : 'success'
}
const getPostStatusText = (posted: number) => {
  return posted == 0 ? '未审核' : '已审核'
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
  },
})

const fetchData = async () => {
  gridApi.reload()
}

// 处理审核
const handleApproval = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({ content: '审核中...', duration: 0, key: 'action_process_msg' })
  try {
    await AuditMstockIn({ ids: getSelectionIds() })
    message.success({ content: '审核成功', key: 'action_process_msg' })
    fetchData()
  } catch {
    hideLoading()
  }
}

// 处理反审
const handleAgainst = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }
  const hideLoading = message.loading({ content: '反审中...', duration: 0, key: 'action_process_msg' })
  try {
    await ReverseMstockIn({ ids: getSelectionIds() })
    message.success({ content: '反审成功', key: 'action_process_msg' })
    fetchData()
  } catch {
    hideLoading()
  }
}

// 导出列表
const handleExportList = async () => {
  const search = await gridApi.formApi.getFiltersValues()
  if (search.length === 0) {
    message.warning('请先选择要导出的数据')
    return
  }
  const hideLoading = message.loading({ content: '导出中...', duration: 0, key: 'action_process_msg' })
  try {
    const { path } = await daochuList({ search })
    window.location.href = path
  } finally {
    hideLoading()
  }
}

// 导出明细
const handleExportDetail = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要导出的数据')
    return
  }
  const hideLoading = message.loading({ content: '导出中...', duration: 0, key: 'action_process_msg' })
  try {
    const response = await daochuDetail({ ids: getSelectionIds() })
    window.location.href = response.path
    // message.success({ content: '导出成功', key: 'action_process_msg' })
  } catch {
    hideLoading()
  }
}

// 批量导入
const handleImport = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.addEventListener('change', async (e: any) => {
    const file = e.target.files[0]
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)

    const hideLoading = message.loading({ content: '导入中...', duration: 0, key: 'action_process_msg' })
    try {
      await batchImportStockin(formData)
      message.success({ content: '导入成功', key: 'action_process_msg' })
      fetchData()
    } catch {
      hideLoading()
    }
  })
  input.click()
}

// 新建
const handleshowFormData = (row: RowType) => {
  FormModalApi.setData({
    info: row,
  }).open()
}
const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})

// 删除处理
const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }

  const disabledApproval = computed(() => {
    return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.Posted >= 1)
  })

  if (disabledApproval.value) {
    message.warning('已审核的数据不能删除')
    return
  }

  const hideLoading = message.loading({
    content: '删除中...',
    duration: 0,
    key: 'action_process_msg',
  })

  doMstockinDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      fetchData()
    })
    .catch(() => {
      hideLoading()
    })
}
const debouncedReload = useDebounceFn(gridApi.reload, 1000)
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleshowFormData({})">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          :disabled="selectedRows.length === 0 || selectedRows.some((row: any) => row.Posted >= 1)"
          title="确认删除"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="selectedRows.length === 0 || selectedRows.some((row: any) => row.Posted >= 1)">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm :disabled="isDisabledApproval" title="确认审核" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button class="mr-2" type="ghost" :class="isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75'" :disabled="isDisabledApproval">审核</Button>
        </Popconfirm>
        <Popconfirm :disabled="isDisabledAgainst" title="确认反审" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button class="mr-2" type="ghost" :class="isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75'" :disabled="isDisabledAgainst">反审</Button>
        </Popconfirm>
        <Button class="mr-2" type="ghost" style="color: white; background-color: #e6a23c" @click="handleExportList">条件导出列表</Button>
        <Button class="mr-2" type="primary" @click="handleExportDetail" :disabled="selectedRows.length === 0">导出明细</Button>
        <Button class="mr-2" type="primary" @click="handleImport">
          <AntUploadOutlined />
          批量导入
        </Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="入库单/生产制单模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #postStatus="{ row }">
        <Tag :color="getPostStatusColor(row.Posted)">
          {{ getPostStatusText(row.Posted) }}
        </Tag>
      </template>
      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="handleshowFormData(row)">编辑</Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
